<template>
	<view class="container">
		<view class="profile-item">
			<view class="content">
				<image :src="outputBase64(imagePath)" class="user-icon" v-if="imagePath" />
				<view class="edit-icon" @click="editPic">✎</view>
			</view>
		</view>

		<view class="profile-item">
			<view class="content">
				<text class="username">{{ userName || '用户名' }}</text>
				<view class="edit-icon2" @click="editName1">✎</view>
			</view>
		</view>
	</view>

	<div v-if="showEdit" class="edit-bar">
		<input type="text" v-model="editName" placeholder="请输入新昵称" maxlength="15" />
		<div class="button-group">
			<button @click="cancelEdit" class="cancel-button">取消</button>
			<button @click="saveEditName" class="save-button">确定</button>
		</div>
	</div>


</template>

<script>
	import appp from '@/applogin.js'
	import api from '../../api/api';
	export default {
		data() {
			return {
				imagePath: '', // 图片的base64
				imagePath1: '', // 上传的图片的路径
				userName: '',
				editName: '',
				showEdit: false, // 控制编辑条显示
			}
		},
		onShow() {
			this.getUserInfo();
		},
		methods: {
			outputBase64(base64Url) {
				/// 获取到base64Data
				var base64Data = base64Url;
				/// 通过微信小程序自带方法将base64转为二进制去除特殊符号，再转回base64
				base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
				/// 拼接请求头，data格式可以为image/png或者image/jpeg等，看需求
				const base64ImgUrl = "data:image/png;base64," + base64Data;
				/// 得到的base64ImgUrl直接给图片:src使用即可
				return base64ImgUrl;
			},
			getUserInfo() {
				api.getUserInfo().then(res => {
					const data = res.data.data
					this.userName = data.nickname
					this.imagePath = data.image
				})
			},
			editName1() {
				this.showEdit = true; // 显示编辑条
			},
			saveEditName() {
				if (this.editName.length > 15) {
					this.editName = this.editName.slice(0, 15); // 超出15个字符时截断
				}
				this.showEdit = false; // 隐藏编辑条
				let obj = {
					userName: this.editName,
					imagePath: '',
					token: uni.getStorageSync('WeTeamToken')
				}
				api.setUserInfo(obj).then(res => {
					this.getUserInfo()
				})
				console.log("新的名字:", this.editName);
			},
			cancelEdit() {
				this.showEdit = false; // 取消编辑
			},
			async editPic() {
				const picPath = await this.choosePic();
				try {
					api.uploadAvatar(this.imagePath1).then(res => {
						let obj = {
							userName: this.userName,
							imagePath: res.data,
							token: uni.getStorageSync('WeTeamToken')
						}
						api.setUserInfo(obj).then(res => {
							this.getUserInfo()
						})
					})
				} catch (error) {
					console.error("上传失败:", error);
					uni.showToast({
						title: '上传失败，请重试',
						icon: 'none'
					});
				}
			},
			removePic() {
				this.imagePath1 = ''
			},
			async choosePic() {
				const that = this;
				try {
					// 将 uni.chooseImage 封装为 Promise
					const imageRes = await new Promise((resolve, reject) => {
						uni.chooseImage({
							count: 1,
							sizeType: ['original', 'compressed'],
							sourceType: ['album'],
							success: resolve,
							fail: reject
						});
					});

					// 取得图片路径
					that.imagePath1 = imageRes.tempFilePaths[0];

					// 将 uni.getFileInfo 封装为 Promise，检查文件大小
					const fileInfoRes = await new Promise((resolve, reject) => {
						uni.getFileInfo({
							filePath: imageRes.tempFilePaths[0],
							success: resolve,
							fail: reject
						});
					});

					// 检查文件大小是否超过2MB
					if (fileInfoRes.size > 2048 * 1024) {
						that.imagePath1 = '';
						uni.showToast({
							title: '图片不超过2MB',
							icon: 'none'
						});
					} else {
						that.imagePath1 = imageRes.tempFilePaths[0]; // 将图片路径赋值
					}

				} catch (error) {
					console.log('选择图片或获取文件信息失败:', error);
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
		/* 使整个页面居中 */
	}

	.profile-item {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 10px 0;
		position: relative;
		/* 便于定位编辑图标 */
	}

	.content {
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.user-icon {
		width: 160px;
		height: 160px;
		border-radius: 50%;
		margin-right: 8px;
		position: relative;
	}

	.username {
		font-size: 20px;
		font-weight: bold;
		margin-right: 8px;
		position: relative;
	}

	.edit-icon {
		width: 42px;
		/* 设置固定宽度 */
		height: 42px;
		/* 设置固定高度 */
		font-size: 36px;
		color: #007bff;
		position: absolute;
		bottom: -5px;
		/* 紧贴图片和用户名的下边缘 */
		right: 20px;
		/* 紧贴图片和用户名的右边缘 */
		background-color: #ffffff;
		/* 背景色 */
		border-radius: 50%;
		/* 圆形背景 */
		display: flex;
		align-items: center;
		/* 垂直居中 */
		justify-content: center;
		/* 水平居中 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		/* 可选：添加阴影 */
	}

	.edit-icon2 {
		width: 30px;
		/* 设置固定宽度 */
		height: 30px;
		/* 设置固定高度 */
		font-size: 24px;
		/* 根据需要调整字体大小 */
		color: #007bff;
		position: absolute;
		bottom: -10px;
		right: -20px;
		background-color: #ffffff;
		/* 背景色 */
		border-radius: 50%;
		/* 圆形背景 */
		display: flex;
		align-items: center;
		/* 垂直居中 */
		justify-content: center;
		/* 水平居中 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		/* 可选：添加阴影 */
	}


	.edit-bar {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: #ffffff;
		padding: 20px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
		border-radius: 8px;
		width: 300px;
		display: flex;
		flex-direction: column;
		align-items: center;
		z-index: 1000;
	}

	.edit-bar input {
		width: 100%;
		padding: 10px;
		margin-bottom: 10px;
		border: 1px solid #007bff;
		border-radius: 4px;
	}

	.button-group {
		display: flex;
		width: 100%;
		gap: 12px;
		/* 按钮之间的间距 */
	}

	.button-group button {
		flex: 1;
		height: 40px;
		/* 设置按钮高度 */
		font-size: 16px;
		/* 调整字体大小 */
		text-align: center;
		/* 水平居中 */
		line-height: 40px;
		/* 设置与高度相同，实现垂直居中 */
		color: #ffffff;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}
	.save-button {
		background-color: #007bff;
	    color: white;
	}
	
	.cancel-button {
	    background-color: #d9d9d9;
	    color: white;
	}

</style>